import { spawn } from 'child_process';
import plist from 'plist';

export default function getApps(resolve, reject, filterByAppName = false) {
  let resultBuffer = Buffer.from([]);
  /**
   * 使用下面的命令获取应用中安装的程序
   */
  const profileInstalledApps = spawn('/usr/sbin/system_profiler', [
    '-xml',
    '-detailLevel',
    'mini',
    'SPApplicationsDataType',
  ]);
  /**
   * 监听data事件，生成返回结果
   */
  profileInstalledApps.stdout.on('data', (chunckBuffer) => {
    resultBuffer = Buffer.concat([resultBuffer, chunckBuffer]);
  });
  /**
   * 命令执行完成了以后，拿到很多应用程序的信息
   */
  profileInstalledApps.on('exit', (exitCode) => {
    if (exitCode !== 0) {
      reject([]);
      return;
    }
    try {
      const [installedApps] = plist.parse(resultBuffer.toString()) as any;
      if (!filterByAppName) return resolve(installedApps._items);
      return resolve(
        installedApps._items.filter((apps) => apps._name === filterByAppName)
          .length !== 0
      );
    } catch (err) {
      reject(err);
    }
  });
  /**
   * 监听error事件，返回错误的处理结果
   */
  profileInstalledApps.on('error', (err) => {
    reject(err);
  });
}
